// ShopCart模块的小仓库
import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}
const actions = {
        // 获取购物车列表数据
        async getCartList({ commit }) {
            let result = await reqCartList()
            if (result.code == 200) {
                commit('GETCARTLIST', result.data)
            }
            // console.log(result)
        },
        // 删除购物车产品数据
        async deleteCartListBySkuId({ commit }, skuId) {
            let result = await reqDeleteCartById(skuId)
            if (result.code == 200) {
                return 'OK'
            } else {
                return Promise.reject(new Error('Failed Delete'))
            }
        },
        //修改购物车某一个产品选中状态
        async updateCheckedById({ commit }, { skuId, isChecked }) {
            let result = await reqUpdateCheckedById(skuId, isChecked)
            if (result.code == 200) {
                return 'OK'
            } else {
                return Promise.reject(new Error('Failed Update'))
            }
        },
        // 删除全部选中产品数据
        deleteAllCheckedCart({ dispatch, getters }) {
            // context 小仓库 commit[提交mutations修改state] getters[计算属性] dispatch[派发action] state[当前仓库数据]
            // 获取购物车中产品信息
            let promiseAll = []
            getters.cartList.cartInfoList.forEach(item => {
                let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : ""
                    // 将每一次返回的promise添加到数组当中
                promiseAll.push(promise)
            });
            // 只有全部Promise对象返回成功 结果才为成功
            // 如果有一个失败 即为失败结果
            return Promise.all(promiseAll)
        },
        // 修改全部产品状态
        updateAllCartChecked({ dispatch, state }, isChecked) {
            let promiseAll = []
            state.cartList[0].cartInfoList.forEach(item => {
                let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
                promiseAll.push(promise)
            })
            return Promise.all(promiseAll)
        },
    }
    // getters 简化数据
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
    // 计算出购物车数据
}

export default {
    state,
    mutations,
    actions,
    getters
}